package com.capinfo.accumulation.service.collection.impl;


import com.capinfo.accumulation.model.collection.CompanyAccountHistory;
import com.capinfo.accumulation.model.collection.CompanyHistory;
import com.capinfo.accumulation.parameter.collection.CompanyHistoryParameter;
import com.capinfo.accumulation.service.collection.CompanyHistoryService;
import com.capinfo.accumulation.service.collection.CompanyUtilService;
import com.capinfo.framework.dao.SearchCriteriaBuilder;
import com.capinfo.framework.dao.impl.restriction.RestrictionExpression;
import com.capinfo.framework.exception.ObjectNotFoundException;
import com.capinfo.framework.service.impl.CommonsDataOperationServiceImpl;
import com.capinfo.framework.util.LogUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;


/**
 * Created by Rexxxar on 2017/9/28.
 */

public class CompanyHistoryServiceImpl extends CommonsDataOperationServiceImpl<CompanyHistory,CompanyHistoryParameter> implements CompanyHistoryService {

    private static final Log logger = LogFactory.getLog(CompanyHistory.class);

    @Autowired
    CompanyUtilService companyUtilService;



    @Override
    public SearchCriteriaBuilder<CompanyHistory> getSearchCriteriaBuilder(CompanyHistoryParameter parameter) {

        SearchCriteriaBuilder<CompanyHistory> searchCriteriaBuilder = super.getSearchCriteriaBuilder(parameter);
        searchCriteriaBuilder.addQueryCondition("creditCode", RestrictionExpression.LIKE_OP, parameter.getEntity().getCreditCode());
        searchCriteriaBuilder.addQueryCondition("competentCode", RestrictionExpression.LIKE_OP, parameter.getEntity().getCompetentCode());
        //根据单位账号查询
        //fjs
        searchCriteriaBuilder.addQueryCondition("gbCompanyAccount", RestrictionExpression.EQUALS_OP, parameter.getEntity().getGbCompanyAccount());
        return searchCriteriaBuilder;
    }

    public CompanyHistory saveOrUpdate(CompanyHistoryParameter parameter) {

        CompanyHistory source = parameter.getEntity();
        CompanyAccountHistory sourceAccount = parameter.getCompanyAccount();

        Class<CompanyHistory> entityClazz = parameter.getEntityClazz();
        Class<CompanyAccountHistory> entityClazzAccount = parameter.getEntityClazzAccount();

        Long id = (null == parameter.getId()) ? source.getId() : parameter.getId();

        if (null == id) {

            try {

                parameter.getEntity().addAccountHistory(parameter.getCompanyAccount());
                /*特殊开户菜单，如组织机构代码和统一社会信用代码都没有，调接口生成一个虚拟的组织机构代码
                加在单位历史信息表里*/
                //判断是否有此组织机构代码或者统一社会信用代码

                if (parameter.getFlag().equals(1L) || null == parameter.getFlag()) ;
                {
                    if (StringUtils.isBlank(parameter.getEntity().getCreditCode())) {
                        String Code;
                        Code = companyUtilService.generateBaseCompanyCode();
                        /*Code ="91310106MA1FY1RF54" ;*/

                        parameter.getEntity().setGbOrganizationCode(Code);

                    }
                }

                getGeneralService().persist(source);

                return source;
            } catch (Exception e) {

                LogUtils.debugException(logger, e);
                throw e;
            }
        } else {

            try {
                CompanyHistory entity = getGeneralService().getObjectById(entityClazz, id);
                //根据单位公积金ID companyAccountFundId查询
                //表单提交的不过滤，表单不提交的过滤掉

                CompanyAccountHistory entityAccount;

                getGeneralService().fetchLazyProperty(entity, "companyAccountHistories");
                if (entity.getCompanyAccountHistories().size() == 1) {

                    entityAccount = entity.getCompanyAccountHistories().get(0);
                    if (sourceAccount.equals(entityAccount)) {

                        BeanUtils.copyProperties(sourceAccount, entityAccount, new String[]{"id", "companyAccountFundId", "companyAccountFund", "companyHistoryId", "companyHistory",
                                "companyAccount", "companyPaymentNumber", "gbdwzhzt", "companyAccountStateId", "companyAccountState", "company_Close_Date", "company_Account_Balance", "company_Deposit_Number",
                                "company_Payment_Date", "companyCloseReasonId", "companyCloseReason", "gbCompanyCloseReason", "depositRateMark", "accumulationFundAccountTypeId", "accumulationFundAccountType",
                                "delegationPaymentId", "preTotalAmount", "totalInterest", "interest", "preMonthPayMonth", "lastPayMonth", "openDate", "startPayMonth", "bankCode", "operatorId", "operator",
                                "regionId", "region", "confirmerId", "confirmer", "confirmationTime", "channels", "createName"});
                    }
                }

                BeanUtils.copyProperties(source, entity, new String[]{"companyId", "gbOrganizationCode", "gbCompanyAccount", "companyInsideClassification", "organizationType", "gbCompanyEconomicType", "companyEconomicType",
                        "gbCompanyIndustries", "companyIndustriesId", "companyIndustries", "gbCompanyRelationships", "gbCompanyPostCode", "gbCompanyEmail", "gbCompanyCreationDate", "gbLegalPersonIdCardType",
                        "legalPersonIdCardType", "gbAgentName", "gbAgentIdCardType", "agentIdCardTypeId", "agentIdCardType", "gbAgentIdCardNumber", "gbAgentMobilePhone", "gbAgentTelephone", "gbTrusteeBank",
                        "gbTrusteeBankCode", "delegationBranch", "delegationBranchCode", "region", "contactAddress", "unitCode", "restDay", "responCode", "newFlag", "custNo", "manageState", "operatorId", "operator", "bankCode",
                        "confirmerId", "confirmer", "channels", "confirmationTime", "createName", "company", "companyAccountHistories"});


                getGeneralService().update(entity);

                //保存成功之后将一些数据返回
                return entity;
            } catch (Exception e) {

                LogUtils.debugException(logger, e);
                throw e;
            }
        }

        /*return super.saveOrUpdate(parameter);*/
    }


    public CompanyHistory getCompanyHistoryById(Long id) {
        CompanyHistory companyHistory = null;
        //级联查询，根据Id得到单位信息历史和单位公积金历史
        try {
            companyHistory = getGeneralService().getObjectById(CompanyHistory.class, id);

        } catch (ObjectNotFoundException e) {
            LogUtils.debugException(logger, e);
        }
        return companyHistory;
    }

    @Override
    public boolean auditInfo(Long id, Long companyId, Long confirmerId) {
        CompanyHistory companyHistory = null;
        CompanyAccountHistory companyAccountHistory = null;

        Boolean token = false;
        companyHistory = getGeneralService().getObjectById(CompanyHistory.class, id);
        if (companyHistory != null) {

            Date date = new Date();
            try {

                getGeneralService().fetchLazyProperty(companyHistory, "companyAccountHistories");
                companyAccountHistory = companyHistory.getCompanyAccountHistories().get(0);
                companyAccountHistory.setConfirmerId(confirmerId);
                companyAccountHistory.setConfirmationTime(date);

                //根据ID，更新单位历史表和单位公积金历史表
                //单位历史表和单位公积金历史表是一对多关系
                companyHistory.setCompanyId(companyId);
                companyHistory.setConfirmerId(confirmerId);

                companyHistory.setConfirmationTime(date);

                getGeneralService().update(companyHistory);
                token = true;
            } catch (Exception e) {

                LogUtils.debugException(logger, e);
            }
        }

        return token;
    }


 /*   public List<CompanyHistory> list(CompanyHistoryParameter parameter) {

        CompanyHistory companyHistory = parameter.getEntity();

        SearchCriteriaBuilder<CompanyHistory> searchCriteriaBuilder = new SearchCriteriaBuilder<CompanyHistory>(CompanyHistory.class);

        searchCriteriaBuilder.addQueryCondition("gbCompanyAccount", RestrictionExpression.EQUALS_OP, parameter.getEntity().getGbCompanyAccount());

        List<CompanyHistory> companyHistories = this.getGeneralService().getObjects(searchCriteriaBuilder.build());
        List<CompanyHistory> siteList = new ArrayList<>();
        if (companyHistories == null || companyHistories.size() == 0)
            return null;
        else {
            for (int i = 0; i < companyHistories.size(); i++) {
                if (!companyHistories.get(i).getPaymentSite().equals(companyHistories.get(i + 1).getPaymentSite())) ;
                siteList.add(companyHistories.get(i));
            }

        }
        return siteList;
    }*/

    //网点变更list
    public List<CompanyHistory> getList(CompanyHistoryParameter parameter, long dataTotalCount, int currentPieceNum) {

        SearchCriteriaBuilder<CompanyHistory> searchCriteriaBuilder = new SearchCriteriaBuilder<CompanyHistory>(CompanyHistory.class);
        searchCriteriaBuilder.addQueryCondition("gbCompanyAccount", RestrictionExpression.EQUALS_OP, parameter.getEntity().getGbCompanyAccount());
        searchCriteriaBuilder.addOrderCondition("id","desc");
        int perPieceSize = (0 < parameter.getPerPieceSize()) ? parameter.getPerPieceSize() : getPerPieceSize();
        searchCriteriaBuilder.addLimitCondition(getDataOffset(dataTotalCount, currentPieceNum, perPieceSize), perPieceSize);

        List<CompanyHistory> companyHistories = this.getGeneralService().getObjects(searchCriteriaBuilder.build());
        List<CompanyHistory> siteList = new ArrayList<CompanyHistory>();
        try {
            if (companyHistories == null || companyHistories.size() == 0)
                return null;
            else {
                for (int i = 0; i < companyHistories.size()-1; i++) {
                    if (!companyHistories.get(i).getPaymentSite().equals(companyHistories.get(i + 1).getPaymentSite()))
                    siteList.add(companyHistories.get(i));
                }
               siteList.add(companyHistories.get(companyHistories.size()-1));
            }
        }catch(Exception e){

            LogUtils.debugException(logger, e);
        }
        return siteList;
    }

    //网点变更历史保存
   //fjs
    @Override
    public CompanyHistory saveChangesite(CompanyHistoryParameter parameter) {

        CompanyHistoryParameter historyParameter = new CompanyHistoryParameter();
        historyParameter.getEntity().setId(parameter.getCompanyHistoryId());

        CompanyHistory companyHistoryRecord = this.getObjectById(historyParameter);


        companyHistoryRecord.setPaymentSite(parameter.getEntity().getPaymentSite());

        companyHistoryRecord.setPreviousId(parameter.getCompanyHistoryId());

        companyHistoryRecord.setConfirmationTime(parameter.getEntity().getConfirmationTime());

        companyHistoryRecord.setOperatorId(parameter.getCompanyAccount().getOperatorId());

        companyHistoryRecord.setId(null);

        getGeneralService().clear();

        getGeneralService().persist(companyHistoryRecord);

        return companyHistoryRecord;

    }

    //单位信息变更历史list
    public List<CompanyHistory> getCompanyInfoChangeList(CompanyHistoryParameter parameter, long dataTotalCount, int currentPieceNum) {

        SearchCriteriaBuilder<CompanyHistory> searchCriteriaBuilder = new SearchCriteriaBuilder<CompanyHistory>(CompanyHistory.class);
        searchCriteriaBuilder.addQueryCondition("id", RestrictionExpression.EQUALS_OP, parameter.getEntity().getId());

       /* int perPieceSize = (0 < parameter.getPerPieceSize()) ? parameter.getPerPieceSize() : getPerPieceSize();
        searchCriteriaBuilder.addLimitCondition(getDataOffset(dataTotalCount, currentPieceNum, perPieceSize), perPieceSize);
*/
        //获取第一条数据放到companyHistories列表
        List<CompanyHistory> companyHistories = this.getGeneralService().getObjects(searchCriteriaBuilder.build());
        CompanyHistory curCompanyHistory =companyHistories.get(0);
        //调用loadPreviousHistory方法查找上一条历史记录
        if(companyHistories != null && companyHistories.size() >0 && curCompanyHistory.getPreviousId() !=null) {
            loadPreviousHistory(companyHistories,curCompanyHistory);
        }
        //单位信息修改的历史（排除site修改的历史）
        List<CompanyHistory> changeInfoList = new ArrayList<CompanyHistory>();
        try {
            if (companyHistories == null || companyHistories.size() == 0)
                return null;
            else {
                for (int i = 0; i < companyHistories.size()-1; i++) {
                    if (companyHistories.get(i).getPaymentSite().equals(companyHistories.get(i + 1).getPaymentSite()))
                        changeInfoList.add(companyHistories.get(i));
                }
                changeInfoList.add(companyHistories.get(companyHistories.size()-1));
            }
        }catch(Exception e){

            LogUtils.debugException(logger, e);
        }
        return changeInfoList;
    }

    //根据priviousId检索上一条历史记录的方法
    //fjs
    private void loadPreviousHistory(List<CompanyHistory> cpyList,CompanyHistory curCompanyHistory){

        SearchCriteriaBuilder<CompanyHistory> searchCriteriaBuilder = new SearchCriteriaBuilder<CompanyHistory>(CompanyHistory.class);
        searchCriteriaBuilder.addQueryCondition("id", RestrictionExpression.EQUALS_OP, curCompanyHistory.getPreviousId());
        List<CompanyHistory> lstCpy = this.getGeneralService().getObjects(searchCriteriaBuilder.build());
        if(lstCpy == null || lstCpy.size() ==0)
            return;

        for (CompanyHistory theCpy:lstCpy) {
            if(theCpy.getPreviousId() == null)
                continue;
            cpyList.add(theCpy);
            loadPreviousHistory(cpyList,theCpy);
        }
    }

    //保存单位基本信息更改
    //fjs
    @Override
    public CompanyHistory saveBasicInfoChange(CompanyHistoryParameter parameter) {

        CompanyHistoryParameter historyParameter = new CompanyHistoryParameter();
        historyParameter.getEntity().setId(parameter.getCompanyHistoryId());
        //取出上一条历史数据
        CompanyHistory companyHistoryRecord = this.getObjectById(historyParameter);
        //把当前这条数据的Id设置为下一条历史的previousId
        companyHistoryRecord.setPreviousId(parameter.getCompanyHistoryId());

        companyHistoryRecord.setGbCompanyName(parameter.getEntity().getGbCompanyName());
        companyHistoryRecord.setCompetentCode(parameter.getEntity().getCompetentCode());
        companyHistoryRecord.setCompanyAddress(parameter.getEntity().getCompanyAddress());
        companyHistoryRecord.setCompanyRelatoinships(parameter.getEntity().getCompanyRelatoinships());
        companyHistoryRecord.setCompanyEconomicTypeId(parameter.getEntity().getCompanyEconomicTypeId());
        companyHistoryRecord.setLegalPersonality(parameter.getEntity().getLegalPersonality());
        companyHistoryRecord.setGbLegalPersonName(parameter.getEntity().getGbLegalPersonName());
        companyHistoryRecord.setGbLegalPersonName(parameter.getEntity().getGbLegalPersonName());
        companyHistoryRecord.setLegalPersonIdCardTypeId(parameter.getEntity().getLegalPersonIdCardTypeId());
        companyHistoryRecord.setLegalPersonMobilePhone(parameter.getEntity().getLegalPersonMobilePhone());
        companyHistoryRecord.setContactName(parameter.getEntity().getContactName());
        companyHistoryRecord.setContactIdCardTypeId(parameter.getEntity().getContactIdCardTypeId());
        companyHistoryRecord.setContactIdCardNumber(parameter.getEntity().getContactIdCardNumber());
        companyHistoryRecord.setContactMobilePhone(parameter.getEntity().getContactMobilePhone());
        //确认的操作时间
        companyHistoryRecord.setConfirmationTime(parameter.getEntity().getConfirmationTime());
        //操作员
        companyHistoryRecord.setOperatorId(parameter.getCompanyAccount().getOperatorId());

        companyHistoryRecord.setId(null);

        getGeneralService().clear();

        getGeneralService().persist(companyHistoryRecord);

        return companyHistoryRecord;

    }
}


